package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("images")
public class ImagesController {
    @Autowired
    ServletContext servletContext;

    @RequestMapping(method = RequestMethod.POST)
    public Map upload(MultipartFile upload){
        HashMap map  = new HashMap();
        try {

            String realPath = servletContext.getRealPath("/upload");
            //获取图片的路径/upload/xxxxx.jpg
            String imgUrl = UploadUtil.upload(upload, realPath);
            map.put("uploaded",1);
            map.put("url",imgUrl);
        }catch (Exception e){
            e.printStackTrace();
            map.put("uploaded",0);
            HashMap errorMap  = new HashMap();
            errorMap.put("message",e.getMessage());
            map.put("error",errorMap);
        }

        //返回新生成的图片url
        return map;
    }

}
